package 手写;

class Node {
    Object obj;
    Node pre;
    Node next;

    public Node() {
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }

    public void setPre(Node pre) {
        this.pre = pre;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    public Node(Object obj, Node pre, Node next) {
        super();
        this.obj = obj;
        this.pre = pre;
        this.next = next;
    }
}

public class 手写LinkedList {
    private Node first = null;
    private Node last = null;
    private int size = 0;

    public void add(Object obj) {
        /*
         * 1.指定对象实现结点的添加
         * 2.要对头结点判断是否为空，空的话将指定对象置为头结点
         * 3.不为空，则往last后增加结点
         * 4.要将last置为结点
         */
        Node n = new Node();
        if (first == null) {
            n.setPre(null);
            n.setObj(obj);
            n.setNext(null);
            first = n;
            last = n;
        } else {
            //直接往last后增加新的节点
            n.setPre(last);
            n.setObj(obj);
            n.setNext(null);
            last.setNext(n);
            //再把n结点置为尾结点
            last = n;
        }
        size++;
    }

    public void add(int index, Object obj) {
        //首先找到要插入位置的节点
        Node temp = find(index);
        Node newNode = new Node();
        newNode.obj = obj;
        if (temp != null) {
            newNode.pre = temp.pre;
            temp.pre.next = newNode;
            newNode.next = temp;
            temp.pre = newNode;
        }
        size++;
    }

    public Node find(int index) {
        /*
         * 1.实现结点的遍历
         * 2.还是要先判断头结点是否为空
         */
        Node temp = null;
        if (first != null) {
            temp = first;
        }
        for (int i = 0; i < index; i++) {
            temp = temp != null ? temp.next : null;
        }
        return temp;
    }

    public Object get(int index) {
        if (index < 0 || index >= size) {
            return null;
        }
        Node temp = find(index);
        if (temp != null) {
            return temp.obj;
        }
        return null;
    }

    public void remove(int index) {
        Node temp = find(index);
        if (temp != null) {
            temp.next.pre = temp.pre;
            temp.pre.next = temp.next;
            size--;
        }
    }

    public int size() {
        return size;
    }

    public static void main(String[] args) {
        手写LinkedList list = new 手写LinkedList();
        list.add("杭州");
        list.add("阿里");
        list.add("Java");
        list.add("算法");
        list.remove(1);
        list.add(1, "加油");
        list.add(2, "offer");
        System.out.println(list.size());
        System.out.println(list.get(1));
        System.out.println(list.get(2));
    }
}